import 'package:demo/utils/overlay.dart';
import 'package:demo/widget/picture_in_picture.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class PIPExample extends StatefulWidget {
  const PIPExample({Key? key}) : super(key: key);

  @override
  PIPExampleState createState() => PIPExampleState();
}

class PIPExampleState extends State<PIPExample> {
  final OverlayManager overlayManager = OverlayManager.instance;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("画中画"),
      ),
      body: GridView(
        padding: const EdgeInsets.only(top: 12, left: 12, right: 12, bottom: 12),
        physics: const BouncingScrollPhysics(),
        scrollDirection: Axis.vertical,
        children: List<Widget>.generate(
          20,
          (int index) {
            return GestureDetector(
              onTap: () {
                const String keyName = "test";
                if (overlayManager.exists(keyName)) {
                  overlayManager.remove(keyName);
                }
                overlayManager.insert(
                  context,
                  keyName,
                  (BuildContext context) => PictureInPicture(
                    builder: (BuildContext context, bool isFloating) {
                      return _BumbleBeeRemoteVideo(
                        onRemoveCallback: () async {
                          await PictureInPicture.of(context)!.exitAnimated();
                          overlayManager.remove(keyName);
                        },
                      );
                    },
                    floatingWindowHeight: 168,
                    floatingWindowWidth: 88,
                  ),
                );
              },
              child: Container(
                height: 48,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(4.0)),
                  color: Colors.blue[600],
                ),
                child: Text(
                  "直播$index",
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            );
          },
        ),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 12.0,
          crossAxisSpacing: 12.0,
          childAspectRatio: 1.5,
        ),
      ),
    );
  }
}

class _BumbleBeeRemoteVideo extends StatefulWidget {
  final VoidCallback onRemoveCallback;
  final bool floating;

  const _BumbleBeeRemoteVideo({Key? key, required this.onRemoveCallback, this.floating = false}) : super(key: key);

  @override
  _BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState();
}

class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    print("初始化了播放器");
    _controller = VideoPlayerController.network(
      'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
      videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    );

    _controller.setLooping(true);
    _controller.initialize().then((value) => setState(() {}));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.floating
          ? null
          : AppBar(
              title: Text("播放页面"),
              leading: Builder(
                builder: (BuildContext context) {
                  return CloseButton(
                    onPressed: widget.onRemoveCallback,
                  );
                },
              ),
              actions: [
                IconButton(
                  icon: Icon(Icons.picture_in_picture),
                  onPressed: () {
                    PictureInPicture.of(context)!.startFloating();
                  },
                )
              ],
            ),
      floatingActionButton: widget.floating
          ? null
          : FloatingActionButton(
              onPressed: widget.onRemoveCallback,
              child: Text("释放"),
            ),
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          SizedBox(
            height: double.infinity,
            width: double.infinity,
            child: VideoPlayer(_controller),
          ),
          _ControlsOverlay(controller: _controller),
          VideoProgressIndicator(_controller, allowScrubbing: true),
        ],
      ),
    );
  }
}

class _ControlsOverlay extends StatelessWidget {
  const _ControlsOverlay({Key? key, required this.controller}) : super(key: key);

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        AnimatedSwitcher(
          duration: Duration(milliseconds: 50),
          reverseDuration: Duration(milliseconds: 200),
          child: controller.value.isPlaying
              ? SizedBox.shrink()
              : Container(
                  color: Colors.black26,
                  child: Center(
                    child: Icon(Icons.play_arrow, color: Colors.white, size: 100.0),
                  ),
                ),
        ),
        GestureDetector(
          onTap: () {
            controller.value.isPlaying ? controller.pause() : controller.play();
          },
        ),
      ],
    );
  }
}
